package com.yunzan.sync_netty.server;

import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

import com.yunzan.sync_netty.BraceletsHandler;
import com.yunzan.sync_netty.DefinedBusinessyHandler;
import com.yunzan.sync_netty.cache.ChannelMap;
import com.yunzan.sync_netty.model.data.BraceletsData;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.string.StringDecoder;

public class HexDecoder extends StringDecoder {


	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {

		String HEXES = "0123456789ABCDEF";
	    byte[] req = new byte[msg.readableBytes()];
	    msg.readBytes(req);
	    final StringBuilder hex = new StringBuilder(2 * req.length);

	    for (int i = 0; i < req.length; i++) {
	        byte b = req[i];
	        hex.append(HEXES.charAt((b & 0xF0) >> 4))
	                .append(HEXES.charAt((b & 0x0F)));
	    }
	    String text=new String(req).toString();
	    text=text.trim();
		text=text.replace(" ","");
	    String[] mqs=text.split("\\]");
	    for(int i=0;i<mqs.length;i++) {
	    	String mq=mqs[i]+"]";
			String code = mq.split("\\*")[1];
			//System.out.println("新的数据是" + mq + "数据长度是 " + mq.length());

			//接受的数据是字符串
			ChannelMap.setChannel(code, ctx.channel());
			ChannelMap.setChannelLock(code, new ReentrantLock());
			BraceletsData data = new BraceletsHandler().accept(mq); // 进行业务处理
			doBusiness(data);
			out.add(mq);
		}
	}


	public  void  doBusiness(BraceletsData data){
       DefinedBusinessyHandler.accept(data);

	}


}
